package com.yiduo.outpost.core.security.jwt;

import com.yiduo.outpost.core.security.TokenProvider;
import com.yiduo.outpost.core.model.constant.SecurityConstant;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.Optional;


public class JwtFilter extends GenericFilterBean {

    private JwtTokenGenerator jwtTokenGenerator;
    private final TokenProvider tokenProvider;

    public JwtFilter(TokenProvider tokenProvider, JwtTokenGenerator jwtTokenGenerator) {
        this.tokenProvider = tokenProvider;
        this.jwtTokenGenerator = jwtTokenGenerator;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // feign或者带token的请求从token里取
        String jwt = extractToken(httpServletRequest);
        if (StringUtils.hasText(jwt) && this.jwtTokenGenerator.validateToken(jwt)) {
            //获取当前用户会话信息
            Authentication authentication = this.tokenProvider.getAuthentication(jwt);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = Optional.ofNullable(request.getHeader(SecurityConstant.AUTHORIZATION_HEADER)).orElse(request.getParameter(SecurityConstant.AUTHORIZATION_HEADER));
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(SecurityConstant.BEARER_PREFIX)) {
            return bearerToken.substring(SecurityConstant.BEARER_PREFIX.length());
        }
        return null;
    }

}
